package UserServices;

import ModeloDominio.Medico;
import ModeloDominio.Morada;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author JON KILL
 */
public class User {

    @PersistenceContext
    private EntityManager em;
    /**
     * <p>The transaction resource.</p>
     */
    @Resource
    private UserTransaction utx;
    private String username;
    private String password;
    private String rule;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRule() {
        return rule;
    }

    public void setRule(String rule) {
        this.rule = rule;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String Login() {


        List cats = null;
        try {
            utx.begin();
            javax.persistence.Query q = em.createQuery("SELECT L.roles FROM Logging L WHERE L.password='" + password + "' and L.username='" + username + "'");
//            if(q.getResultList()!=null)
            cats = q.getResultList();
            utx.commit();
        } catch (Exception ex) {
            Logger.getLogger(Utentes.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (cats.size()==0) {
            FacesContext context = FacesContext.getCurrentInstance();
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Login Failed!´",
                    "The password or username specified is not correct.");
            context.addMessage(null, message);
        } else {
            String rol = (String) cats.get(0);
            if (rol.compareTo("DENTISTA") == 0) {
                return "SISOMainMD";
            }
            if (rol.compareTo("MFAMILIA") == 0) {
                return "SISOMainMF";
            }
            if (rol.compareTo("ARS") == 0) {
                return "SISOMainARS";
            }
            if (rol.compareTo("ACSS") == 0) {
                return "SISOMainACSS";
            }
            if (rol.compareTo("RNU") == 0) {
                return "SISOMainRNU";
            }
        }
        return null;
    }
}
